package com.yy.yunpan.share.controller;

import com.yy.yunpan.common.result.Result;
import com.yy.yunpan.share.entity.Share;
import com.yy.yunpan.share.service.ShareService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 分享管理控制器
 *
 * @author YY
 * @since 2025-10-01
 */
@RestController
@RequestMapping("/api/share")
@Tag(name = "分享管理", description = "文件分享相关接口")
public class ShareController {

    @Autowired
    private ShareService shareService;

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        return (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    @PostMapping("/create")
    @Operation(summary = "创建分享")
    public Result<Share> createShare(
            @RequestParam Long fileId,
            @RequestParam String shareName,
            @RequestParam(defaultValue = "2") Integer permissions,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String expireTimeStr) {

        Long userId = getCurrentUserId();

        // 解析过期时间
        LocalDateTime expireTime = null;
        if (expireTimeStr != null && !expireTimeStr.trim().isEmpty()) {
            try {
                expireTime = LocalDateTime.parse(expireTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (Exception e) {
                return Result.error(400, "过期时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
            }
        }

        Share share = shareService.createShare(userId, fileId, shareName, permissions, password, expireTime);
        return Result.success(share);
    }

    @GetMapping("/{shareCode}")
    @Operation(summary = "访问分享")
    public Result<Map<String, Object>> getShare(@PathVariable String shareCode) {
        Map<String, Object> shareInfo = shareService.getShareByCode(shareCode);

        // 增加访问次数（仅在无需密码或已验证的情况下）
        if (!(Boolean) shareInfo.get("needPassword")) {
            shareService.incrementVisitCount(shareCode);
        }

        return Result.success(shareInfo);
    }

    @PostMapping("/{shareCode}/verify")
    @Operation(summary = "验证分享密码")
    public Result<Map<String, Object>> verifySharePassword(
            @PathVariable String shareCode,
            @RequestParam String password) {

        Map<String, Object> result = shareService.verifySharePassword(shareCode, password);
        return Result.success(result);
    }

    @GetMapping("/my/list")
    @Operation(summary = "获取我的分享列表")
    public Result<Page<Share>> getMyShareList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(defaultValue = "createTime") String orderBy,
            @RequestParam(defaultValue = "desc") String orderType) {

        Long userId = getCurrentUserId();
        Page<Share> sharePage = shareService.getUserShareList(userId, page, size, orderBy, orderType);
        return Result.success(sharePage);
    }

    @PostMapping("/{shareId}/cancel")
    @Operation(summary = "取消分享")
    public Result<Void> cancelShare(@PathVariable Long shareId) {
        Long userId = getCurrentUserId();
        shareService.cancelShare(userId, shareId);
        return Result.success();
    }

    @PostMapping("/{shareId}/update")
    @Operation(summary = "更新分享设置")
    public Result<Share> updateShare(
            @PathVariable Long shareId,
            @RequestParam(required = false) String shareName,
            @RequestParam(required = false) Integer permissions,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String expireTimeStr) {

        Long userId = getCurrentUserId();

        // 解析过期时间
        LocalDateTime expireTime = null;
        if (expireTimeStr != null && !expireTimeStr.trim().isEmpty()) {
            try {
                expireTime = LocalDateTime.parse(expireTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (Exception e) {
                return Result.error(400, "过期时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
            }
        }

        Share share = shareService.updateShare(userId, shareId, shareName, permissions, password, expireTime);
        return Result.success(share);
    }

    @PostMapping("/{shareCode}/download")
    @Operation(summary = "分享文件下载统计")
    public Result<Void> recordDownload(@PathVariable String shareCode) {
        shareService.incrementDownloadCount(shareCode);
        return Result.success();
    }
}